#include"InetAddr.hpp"
#include"Comm.hpp"

#include<iostream>
#include<string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<unistd.h>
// #include<ctsdint>


void Usage(std::string proc)
{
    std::cerr << "Usage " << proc <<" serverip serverport" << std::endl;
}

//./client serverip serverport
int main(int argc , char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    InetAddr server(serverport , serverip);

    //创建套接字
    int sockfd = socket(AF_INET , SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "创建套接字失败" << std::endl;
        exit(SOCKET_CREATE_ERR);
    }

    //客户端向服务器发起连接，的时候OS会自动bind 
    //connect 成功返回0，失败返回-1
    if( connect(sockfd , server.Addr() ,server.Length()) < 0)
    {
        std::cerr << "客户端连接服务器失败" << std::endl;
        exit(SOCKET_CONNECT_ERR);
    }
    std::cout << "connect " <<server.ToString() << " success" <<std::endl;

    //客户端也是一个死循环
    while(true)
    {
        std::cout << "Please enter#";
        std::string line;
        std::getline(std::cin , line);

        ssize_t n = write(sockfd ,line.c_str() , line.size());//write 返回
        if( n>=0 )
        {
            char buffer[1024];
            int m = read(sockfd , buffer , sizeof(buffer)-1);
            if(m >0)
            {
                buffer[m]=0;
                std::cout << buffer << std::endl;
            }
        }
    }

    return 0;
}